package com.example.demo.utils;

import cn.hutool.core.map.MapUtil;
import com.example.demo.utils.Constant;
import org.apdplat.word.WordSegmenter;
import org.apdplat.word.segmentation.Word;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class wordCountHelper {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final  Pattern p = Pattern.compile("[a-zA-Z]|[0,9]");
    private final String stop="在,点击,能,进入,去,一个,打开,出现,不,只,无法,却,应,该,应该,中,才,没有,面无,无,已,但是,虽然,可,未,还,是,界,发现";
    private  HashSet<String> stopWords;

    @PostConstruct
    private void init(){
        stopWords=new HashSet<>(Arrays.asList(stop.split(",")));
    }

    public List<String> getWordsByTid(int tid){
        ArrayList<String> result=new ArrayList<>();
        String key= Constant.WORD_MAP_TOKEN+tid;
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
        for(Map.Entry<Object,Object> entry: entries.entrySet()){
            result.add((String) entry.getKey());
        }
        return result;
    }



    public Map<String,Integer> countWordAndSave(String sentence,int tid){
        Map<String,Integer> result=countWord(sentence);
        String key= Constant.WORD_MAP_TOKEN+tid;
        Map<String,String> toSave=new HashMap<>();
        for(Map.Entry<String,Integer> entry:result.entrySet()){
            toSave.put(entry.getKey(),entry.getValue().toString());
        }
        //
        stringRedisTemplate.opsForHash().putAll(key,toSave);
        //从redis取出map
//        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
//        int r = Integer.parseInt((String) entries.get("测试"));

        return result;

    }

    public Map<String,Integer> countWord(String sentence) {
        List<Word> words = WordSegmenter.seg(sentence);
        HashMap<String,Integer> map =new HashMap<>();

        for(Word word:words){
            String s=word.toString();
            if (isValidWord(s))
                map.put(s,map.getOrDefault(s,0)+1);
        }

//        for(Map.Entry<String,Integer> entry:map.entrySet()){
//            System.out.println(entry.getKey()+"："+entry.getValue());
//        }
        return map;

    }


    /**
     * 去除识别不出的单个英文字母，去除自定义停用词
     * @param s
     * @return
     */
    private  boolean isValidWord(String s){
        Matcher matcher = p.matcher(s);
        return !(matcher.matches()||stopWords.contains(s));

    }
}
